package com.jxs.android.weixi;

import java.io.IOException;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.widget.TextView;

import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.util.MemoryUtil;
import com.jxs.android.util.StartHelper;
import com.jxs.android.util.StringUtils;
import com.jxs.android.weiget.BuAlertDailog;
import com.jxs.android.weiget.BuLoadingDailog;
import com.jxs.android.weiget.LockPatternView;
import com.jxs.android.weiget.TopBar;
import com.telecom.weixi.R;
import com.telecom.weixi.util.CryptUtil;

@SuppressLint("HandlerLeak")
public class LaucherSystemMore_ChangePwd extends AbstractActivity {
	private LockPatternView lockPatternView;
	private Context context;
	private BuLoadingDailog buLoadingDailog;
	private String imsi = "460036520427761";
	private TextView bu_more_change_pwd_tip;
	private boolean oldPasswordInput = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		context = this;
		initLoadingView();
		super.initTopBar(savedInstanceState, R.layout.bu_sys_more_change_pwd);
		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		imsi = null == tm.getSubscriberId() ? "" : tm.getSubscriberId();
		if (StringUtils.isEmpety(imsi)) {
			errorMsgPop(R.string.error_not_has_sim, new BuAlertDailog.IPhoneAlertDailog() {
				@Override
				public void okLogic(Dialog dialog) {
					finish();
				}

				@Override
				public String getOkText(Context context) {
					return null;
				}
			});
		}
		imsi = "460030309442061";// new

		bu_more_change_pwd_tip = (TextView) findViewById(R.id.bu_more_change_pwd_tip);

		lockPatternView = (LockPatternView) this.findViewById(R.id.lock_pattern);
		lockPatternView.setCheckConfirmListener(new LockPatternView.ICheckConfrim() {

			@Override
			public void onLockPattern(boolean bInit, boolean matched) {
				if (bInit) {

					String password = lockPatternView.getPathWord();
					if (oldPasswordInput) {
						buLoadingDailog.showLoading(R.string.tip_user_login);
						updatePattern(WeixiApplication.getUserInfo().getPassword(), password);
					} else {
						if (password.equals(WeixiApplication.getUserInfo().getPassword())) {
							bu_more_change_pwd_tip.setText(R.string.bu_more_change_pwd_tip_new_pwd);
							oldPasswordInput = true;
							errorMsgPop("匹配成功，请设置新解锁码！");
						} else {
							errorMsgPop(R.string.bu_more_change_pwd_tip_old_pwd_fail);
						}
					}

					lockPatternView.resetGraphData();
					lockPatternView.resetState();
				}
			}
		}, this);
	}

	@Override
	public void topBarLogic(TopBar topBar) {
		topBar.hindBtn();
		topBarReturn(topBar);
		topBar.setTitle(R.string.bu_more_change_pwd);
	}

	private void initLoadingView() {
		buLoadingDailog = new BuLoadingDailog(context);
		buLoadingDailog.setLoadingListener(new BuLoadingDailog.LoadingListener() {

			@Override
			public void okLogic(Dialog dialog) {
				dialog.dismiss();
			}

			@Override
			public String getOkText(Context context) {
				return getString(R.string.prompt_confirm);
			}
		});
	}

	private void updatePattern(final String oldPasword, final String newPasword) {
		final CryptUtil crypt = CryptUtil.getInstance();
		new Thread(new Runnable() {

			@Override
			public void run() {
				String wsdl_url = WeixiApplication.WSDL_URL;// wsdl
				String namespace = WeixiApplication.WSDL_NAME_SPACE;// namespace
				String methodName = "updatePattern";// 要调用的方法名称
				SoapObject request = new SoapObject(namespace, methodName);

				request.addProperty("imeiCode", crypt.encryptAES(((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId(), CryptUtil.getKey()));
				request.addProperty("imsiCode", crypt.encryptAES(imsi, CryptUtil.getKey()));
				request.addProperty("oldPassword", crypt.encryptAES(oldPasword, CryptUtil.getKey()));
				request.addProperty("newPassword", crypt.encryptAES(newPasword, CryptUtil.getKey()));
				BuWebService webService = new BuWebService(wsdl_url, request);
				webService.setDoNet(false);
				webService.requestWSDL(new IWebService() {
					@Override
					public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
						paserResponse(envelope.getResponse().toString());
					}

					@Override
					public void error(String message, Exception e) {
						Message msg = new Message();
						msg.what = ERROR_MSG;
						msg.obj = message;
						handler.sendMessage(msg);
					}
				});
			}
		}).start();
	}

	private void paserResponse(String stauts) {
		if ("0".equals(stauts)) {// 修改失败
			handler.sendEmptyMessage(ERROR_MSG);
		} else if ("1".equals(stauts)) {// 修改成功
			handler.sendEmptyMessage(RESULT_OK);
		}
	}

	private int RESULT_OK = 0x110;
	private int ERROR_MSG = 0x112;

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (MemoryUtil.isCurrentActivity(LaucherSystemMore_ChangePwd.class)) {// 判断是不是当前的Activity
				if (null != buLoadingDailog && buLoadingDailog.isShowing()) {
					buLoadingDailog.dismiss();
				}
				if (msg.what == RESULT_OK) {
					errorMsgPop("密码已修改，请重新登陆", new BuAlertDailog.IPhoneAlertDailog() {
						@Override
						public void okLogic(Dialog dialog) {
							dialog.cancel();
							StartHelper.startActivity(Login.class);
							finish();
						}

						@Override
						public String getOkText(Context context) {
							return getString(R.string.prompt_confirm);
						}
					});

				} else if (msg.what == ERROR_MSG) {
					errorMsgPop(R.string.bu_more_change_pwd_tip_new_pwd_fail, new BuAlertDailog.IPhoneAlertDailog() {

						@Override
						public void okLogic(Dialog dialog) {
							dialog.cancel();
							bu_more_change_pwd_tip.setText(R.string.bu_more_change_pwd_tip_old_pwd);
							oldPasswordInput = false;
						}

						@Override
						public String getOkText(Context context) {
							return null;
						}
					});
				}
			}
		}

	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return false;
	}

}